import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Typography,
  Tag,
  Tree,
  Tooltip,
  Popover,
} from '@arco-design/web-react';
import type { TableColumnProps } from '@arco-design/web-react';
import PermissionWrapper from '@/components/PermissionWrapper';
import { IconDownload, IconPlus } from '@arco-design/web-react/icon';
import axios from 'axios';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import './mock';
import KeepAlive, { useActivate, useAliveController } from 'react-activation';
import { useHistory } from 'react-router-dom';
import { DetailModal } from './detailModal';
import * as Model from '@/services/model';
import { IRoute, routes } from '@/routes';
import { TreeDataType } from '@arco-design/web-react/es/Tree/interface';
const { Title } = Typography;
const actionList = {
  insert: '新增',
  delete: '删除',
  update: '编辑',
  select: '查找',
  import: '导入',
  export: '导出',
};
function SearchTable() {
  const t = useLocale(locale);
  const globalLocale = useLocale();
  const history = useHistory();

  const [roleDetail, setRoleDetail] = useState<Model.Role.default | false>(
    false
  );
  const generateTreeData = (e: IRoute): TreeDataType => {
    const title = globalLocale[e.name];
    const titleRender =
      e.children?.length > 0 ? (
        title
      ) : (
        <Popover
          title="操作权限"
          content={
            <Space>
              {Object.values(actionList).map((f) => (
                <Tag size="small" color="blue" key={f}>
                  {f}
                </Tag>
              ))}
            </Space>
          }
        >
          {title}
        </Popover>
      );

    return {
      title: titleRender,
      key: e.key,
      children:
        e.children?.length > 0
          ? e.children.map((f) => generateTreeData(f))
          : null,
    };
  };
  const columns: TableColumnProps[] = [
    { title: 'ID', dataIndex: 'id' },
    { title: '角色', dataIndex: 'role' },
    {
      title: '页面权限',
      dataIndex: 'permissions',
      render: (col) => {
        const treeData = routes.map((e) => generateTreeData(e));
        return <Tree autoExpandParent treeData={treeData}></Tree>;
      },
    },

    {
      title: '操作',
      render: (col, item) => {
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={() => setRoleDetail(item)}
            >
              编辑角色
            </Button>

            <Button
              type="default"
              size="small"
              status="danger"
              onClick={() => setRoleDetail(item)}
            >
              删除角色
            </Button>
          </Space>
        );
      },
    },
  ];

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});
  const aliveController = useAliveController();
  useActivate(() => {
    console.log('active');
  });
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    axios
      .get('/api/role/list', {
        params: {
          page: current,
          pageSize,
          ...formParams,
        },
      })
      .then((res) => {
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }

  return (
    <Card>
      <SearchForm onSearch={handleSearch} />
      <div className={styles['button-group']}>
        <Space>
          <Button
            onClick={() => setRoleDetail(new Model.Role.default())}
            type="primary"
            icon={<IconPlus />}
          >
            新增角色
          </Button>

          <Button type="default" icon={<IconDownload />}>
            导出角色
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />

      <DetailModal
        onCancel={() => setRoleDetail(false)}
        onOk={() => setRoleDetail(false)}
        roleInfo={roleDetail}
      />
    </Card>
  );
}

export default SearchTable;
